package com.baocaiqiche.dev.taoforandroid;

import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import okhttp3.Request;
import okhttp3.Response;

public class ListActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

    private SwipeRefreshLayout swipeLayout;
    private MyAdapter adapter ;
    private HttpUtils httpUtils;
    private boolean isRefresh = false , isLoading = false;
    private LinearLayoutManager linearLayoutManager;
    private int lastVisibleItem = 0;
    private Toolbar toolbar;
    private static final String LIST_TAG = "ListActivity" ;
    private Integer page = 1;
    private Integer offect = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        adapter = new MyAdapter();
        httpUtils = new HttpUtils();

        httpUtils.getRequest(getUrl(), new HttpUtils.StringCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                Toast.makeText(ListActivity.this,"加载数据失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) throws IOException {
                Log.d(LIST_TAG,response);
                User user = new User();
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<User>>(){}.getType();
                ArrayList<User> users = gson.fromJson(response,type);
                adapter.addItem(users);
                page += 1;
            }
        });

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(ListActivity.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                User user = adapter.datas.get(position);
                String string = "姓名：" + user.getName() + "\n手机：" + user.getMobile();
                Toast.makeText(ListActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {

                    if(!isRefresh && !isLoading){

                        httpUtils.getRequest(getUrl(), new HttpUtils.StringCallBack() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                isLoading = false;
                                Toast.makeText(ListActivity.this,"加载数据失败",Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(final String response) throws IOException {

                                isLoading = false;
                                User user = new User();
                                Gson gson = new Gson();
                                Type type = new TypeToken<ArrayList<User>>(){}.getType();
                                ArrayList<User> users = gson.fromJson(response,type);
                                page += 1;
                                adapter.addItem(users);
                            }
                        });
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView,dx, dy);
                lastVisibleItem =linearLayoutManager.findLastVisibleItemPosition();
            }
        });

        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        //设置进度条的颜色主题，最多能设置四种 加载颜色是循环播放的，只要没有完成刷新就会一直循环，holo_blue_bright>holo_green_light>holo_orange_light>holo_red_light
        swipeLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED);
        // 设置手指在屏幕下拉多少距离会触发下拉刷新
        swipeLayout.setDistanceToTriggerSync(300);
        // 设定下拉圆圈的背景
        swipeLayout.setProgressBackgroundColorSchemeColor(Color.WHITE);
        // 设置圆圈的大小
        swipeLayout.setSize(SwipeRefreshLayout.LARGE);
        //设置下拉刷新的监听
        swipeLayout.setOnRefreshListener(this);
    }

    public String getUrl(){

        String Url = null;

        int start = (this.page - 1) * this.offect;

        Url = "http://dev.baicaiqiche.com:8000/test.php?start="+ start + "&offect=" + this.offect;

        return Url ;
    }

    @Override
    public void onRefresh() {

        //检查是否处于刷新状态
        if (!isRefresh) {

            isRefresh = true;

            httpUtils.getRequest("http://dev.baicaiqiche.com:8000/test.php?id=43", new HttpUtils.StringCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    swipeLayout.setRefreshing(false);
                    isRefresh = false;
                    Toast.makeText(ListActivity.this,"加载数据失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(final String response) throws IOException {
                    swipeLayout.setRefreshing(false);
                    isRefresh = false;
                    User user = new User();
                    Gson gson = new Gson();
                    Type type = new TypeToken<ArrayList<User>>(){}.getType();
                    ArrayList<User> users = gson.fromJson(response,type);
                    adapter.addMoreItem(users);
                }
            });
        }
    }
}
